from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

# 密钥必须为16、24或32字节长（对应AES-128、AES-192或AES-256）
key = get_random_bytes(32)  # 生成随机密钥
iv = get_random_bytes(16)   # 初始化向量 (IV)，对于CBC模式来说也是必需的
msg = b"hello world; this is a secret message"

# 加密
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypt_msg = cipher.encrypt(pad(msg, AES.block_size))
print("加密后的数据:", encrypt_msg)

# 解密
cipher_decypty = AES.new(key, AES.MODE_CBC, iv)
original_msg = unpad(cipher_decypty.decrypt(encrypt_msg), AES.block_size)

print("解密后的数据",original_msg)